﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Duo1JHttpServer.Framework.Utils
{
    public static class StringUtils
    {
        /// <summary>
        /// 字符串按行分割转化为html
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetLinedHtml(string str, string tag = null)
        {
            string format = "<p>{0}</p>";
            if (tag != null)
            {
                string tempTag = tag;
                if (new Regex(@"<\w+>").IsMatch(tag))
                {
                    tempTag = tag.Substring(1, tag.Length - 2);
                }

                format = $"<{tempTag}>{0}</{tempTag}>";
            }

            StringBuilder res = new StringBuilder();
            string[] splited = str.Split('\n');
            foreach (string line in splited)
            {
                res.Append(string.Format(format, line));
            }

            return res.ToString();
        }

        /// <summary>
        /// 字节数组转字符串
        /// </summary>
        /// <returns></returns>
        public static string BytesToString(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
            {
                sb.Append(Convert.ToChar(b));
            }

            return sb.ToString();
        }
    }
}